<?php

namespace app\admin\controller\service\skill;

use app\admin\library\Auth;
use app\admin\model\service\Goods;
use app\api\model\service\UserInfo;
use app\common\controller\Backend;
use app\common\model\User;
use fast\Http;
use fast\Random;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\Db;
use think\db\exception\BindParamException;
use think\Exception;
use think\exception\PDOException;
use app\admin\model\service\skill\Skill as SkillModel;

/**
 * 服务人员信息管理
 *
 * @icon fa fa-circle-o
 */
class Skill extends Backend
{

    /**
     * Skill模型对象
     * @var \app\admin\model\service\skill\Skill
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\service\skill\Skill;
        $this->view->assign("sexList", $this->model->getSexList());
        $this->view->assign("eduList", $this->model->getEduList());
        $this->view->assign("experList", $this->model->getExperList());
        $this->view->assign("isRestList", $this->model->getIsRestList());
        $this->view->assign("isTrainList", $this->model->getIsTrainList());
        $this->view->assign("stateList", $this->model->getStateList());
    }



    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        foreach ($list as &$val)
        {
            $val->shop_name = $val->shop_id?\app\admin\model\service\shop\Shop::where(['id'=>$val->shop_id])->value('abbr'):'';
            $val->category_name = \app\admin\model\service\Category::where(['id'=>$val->category_id])->value('name');
            $val->skill_cate_name = \app\admin\model\service\skill\Skillcate::getName($val->skill_cate_id);
            $val->goodsname = $val->goods_ids?model('app\admin\model\service\Goods')->getGoodsList($val->goods_ids):'';
            $val->skillmoney = \app\admin\model\service\User::where('user_id',$val->user_id)->field('money,shop_money')->find();
            $val->already_accept_nums = \app\admin\model\service\order\Order::where(['skill_id'=>$val->id,'status'=>['>',1],'starttime'=>['>',strtotime(date("Y-m-d",time()))]])->count();
            $val->update_time = $val->updatetime?date("Y-m-d",$val->updatetime):'';
            $val->create_time = date("Y-m-d",$val->createtime);
        }
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        if($params['city'])
        {
            $address = explode('/',$params['city']);
            $params['province'] = $address[0];
            $params['city'] = $address[1];
            $params['district'] = $address[2]??'';
        }
        $result = false;
        $user = \app\admin\model\service\User::get(['user_id'=>$params['user_id']]);
        $user['is_skill'] == 1 && $this->error('当前用户已申请成为服务者');
        $count = $this->model->where('state',1)->count();
        $params['code'] = str_pad(date('d').$count,8,0);
        $params['state'] = 1;
        $params['updatetime'] = time();
        $params['accept_nums'] = \app\api\model\service\ProjectConfig::getProjectConfig('accept_nums');
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            model('app\admin\model\service\User')->where('user_id',$params['user_id'])->update(['is_skill'=>1]);
            $skill = db('service_skill')->where('user_id',$user['user_id'])->find();
            \app\admin\model\service\skill\Applyskill::createTime($skill['id']);
            unset($skill['id']);
            $skill['applytype'] = 1;
            $perfect = new \app\admin\model\service\skill\Perfect($skill);
            $perfect->allowField(true)->save();
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $row->city = $row->province.'/'.$row->city.'/'.$row->district;
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        if($params['city'])
        {
            $address = explode('/',$params['city']);
            $params['province'] = $address[0];
            $params['city'] = $address[1];
            $params['district'] = $address[2] ?? '';
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    public function deduct($ids = null)
    {
        $row = $this->model->get($ids);
        if($this->request->isPost())
        {
            $params = $this->request->post('row/a');
            Db::startTrans();
            try{
                $params['skill_ensure']>$row->ensure_price && $this->error('保证金不足,无法扣除');
                \app\api\model\service\Skill::money(-$params['skill_ensure'], $row->user_id, $params['skill_note']);
                Db::commit();
                $this->success('保证金已扣除');
            } catch (Exception $e) {
                Db::rollback();
                $this->error('保证金扣除失败',$e->getMessage());
            }
        }
        $this->assign(['row'=>$row]);
        return $this->view->fetch();
    }


    /**
     * 导入
     *
     * @return void
     * @throws PDOException
     * @throws BindParamException
     */
    public function import()
    {
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
//        $filePath = ROOT_PATH . DS . 'public' . DS . 'template/skill.xlsx';
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, 'w');
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding !== 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        $fieldArr = [
            '姓名' => 'name',
            '身份证号码' => 'idcard',
            '电话' => 'mobile',
            '服务技能' => 'skill_cate_id',
            '服务项目' => 'goods_ids',
            '学历' => 'edu',
            '民族' => 'nation',
            '身高/cm' => 'height',
            '体重/kg' => 'weight',
            '经验' => 'exper',
            '省' => 'province',
            '市' => 'city',
            '区' => 'district',
            '地址' => 'address',
            '身份证正面' => 'front_image',
            '身份证反面' => 'opposite_image',
            '订单收益' => 'percent',
            '性别' => 'sex',
        ];

        //加载文件
        $insert = [];
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $fields = [];
            for ($currentRow = 2; $currentRow <= 2; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[] = $val;
                }
            }

            for ($currentRow = 3; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : trim($val);
                }
                $row = [];
                $temp = array_combine($fields, $values);
                foreach ($temp as $k => $v) {
                    if (isset($fieldArr[$k]) && $k !== '') {
                        $row[$fieldArr[$k]] = $v;
                    }
                }
                if ($row) {
                    $insert[] = $row;
                }
            }
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
        if (!$insert) {
            $this->error(__('No rows were updated'));
        }
        //var_dump($insert);die;
        //0=小学文化,1=初中,2=高中,3=大专,4=本科,5=硕士,6=博士
        $edu_map = [
            '小学' => 0,
            '小学文化' => 0,
            '初中' => 1,
            '高中' => 2,
            '大专' => 3,
            '专科' => 3,
            '本科' => 4,
            '硕士' => 5,
            '博士' => 6,
        ];
        Db::startTrans();
        try {
            foreach ($insert as $item) {
                $mobile = $item['mobile'] ?? '';
                if (empty($mobile)) throw new Exception('手机号不能为空');

                $user = User::getByMobile($mobile);
                if (!$user) {
                    $ip = request()->ip();
                    $time = time();
                    $parent_user_id = 0;
                    $username = $mobile;
                    $password = Random::alnum();
                    $data = [
                        'username' => $username,
                        'password' => $password,
                        'email' => '',
                        'mobile' => $mobile,
                        'level' => 1,
                        'score' => 0,
                        'parent_user_id' => $parent_user_id,
                        'avatar' => '',
                    ];
                    $params = array_merge($data, [
                        'nickname' => preg_match("/^1[3-9]{1}\d{9}$/", $username) ? substr_replace($username, '****', 3, 4) : $username,
                        'salt' => Random::alnum(),
                        'jointime' => $time,
                        'joinip' => $ip,
                        'logintime' => $time,
                        'loginip' => $ip,
                        'prevtime' => $time,
                        'status' => 'normal'
                    ]);
                    $params['password'] = md5(md5($password) . $params['salt']);
                    $user = User::create($params, true);
                }

                $uid = $user->id;
                if (!$userInfo = UserInfo::getByMobile($mobile)) {
                    $newUser = ['user_id' => $uid, 'mobile' => $mobile,'is_skill' => 1];
                    UserInfo::create($newUser);
                }else {
                    $userInfo->save(['is_skill' => 1]);
                }

                $item['user_id'] = $uid;
                $count = $this->model->where('state', 1)->count();
                $item['code'] = str_pad(date('d') . $count, 8, 0);
                $item['front_image'] = sprintf('/third/uploads/20240724/%s_1.png', $mobile);
                $item['opposite_image'] = sprintf('/third/uploads/20240724/%s_2.png', $mobile);

                if (!empty($item['skill_cate_id'])) {
                    $cat_list = explode('、', $item['skill_cate_id']);
                    $cat_ids = \app\admin\model\service\skill\Skillcate::whereIn('name', $cat_list)->column('id');
                    $item['skill_cate_id'] = implode(',', $cat_ids);
                }

                if (!empty($item['goods_ids'])) {
                    $goods_list = explode('、', $item['goods_ids']);
                    $goods_ids = Goods::whereIn('name', $goods_list)->column('id');
                    $item['goods_ids'] = implode(',', $goods_ids);
                }

                if (!empty($item['address'])) {
                    $map_url = 'https://restapi.amap.com/v3/geocode/geo';
                    $map_param = [
                        'address' => $item['address'],
                        'city' => empty($item['city']) ? '' : $item['city'],
                        'key' => '5e0d711dc520a746549847425fc5465f',
                    ];
                    $ret = Http::get($map_url, $map_param);
                    $ret = json_decode($ret,true);
                    if (!empty($ret['status']) && $ret['status'] == 1) {
                        if($ret['count']) {
                            $location = $ret['geocodes'][0]['location'];
                            [$lng, $lat] = explode(',', $location);
                            $item['lng'] = $lng;
                            $item['lat'] = $lat;
                        }
                    }
                }


                //0=1年以下,1=1-3年,2=3-5年,3=5年以上
                $exper = $item['exper'];
                if ($exper > 5) {
                    $expInt = 3;
                } elseif ($exper >= 3) {
                    $expInt = 2;
                } elseif ($exper >= 1) {
                    $expInt = 1;
                } else {
                    $expInt = 0;
                }
                $item['exper'] = $expInt;
                $item['edu'] = $edu_map[$item['edu']] ?? 2;

                $item['sex'] = !empty($item['sex']) && $item['sex'] == '男' ? 1 : 0;
                $item['percent'] = empty($item['percent']) ? 0 : intval($item['percent']);

                if (!SkillModel::getByMobile($mobile)) {
                    SkillModel::create($item);
                }
            }

            Db::commit();
        } catch (PDOException $exception) {
            Db::rollback();
            $msg = $exception->getMessage();
            if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
                $msg = "导入失败，包含【{$matches[1]}】的记录已存在";
            }
            $this->error($msg);
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success();
    }

}
